#!/usr/bin/env python3
import argparse
import sys
import time
from pathlib import Path

from rich.console import Console
from rich.markdown import Markdown
from watchdog.events import FileSystemEventHandler
from watchdog.observers import Observer

class MarkdownHandler(FileSystemEventHandler):
    """文件变更处理器"""
    def __init__(self, file_path, console):
        super().__init__()
        self.file_path = file_path
        self.console = console
        self.last_content = None

    def render_markdown(self):
        """渲染并显示 Markdown 内容"""
        try:
            content = self.file_path.read_text(encoding="utf-8")
            if content == self.last_content:
                return
            self.last_content = content
            
            self.console.clear()
            markdown = Markdown(content)
            self.console.print(markdown)
            self.console.print(f"\n[bold green]✓ 正在监视: {self.file_path} (Ctrl+C 退出)")
        except Exception as e:
            self.console.print(f"[bold red]错误: {str(e)}", style="red")

    def on_modified(self, event):
        """文件修改时触发"""
        if event.src_path == str(self.file_path):
            self.render_markdown()

def main():
    # 初始化命令行参数解析
    parser = argparse.ArgumentParser(description="Markdown 实时预览工具")
    parser.add_argument("file", help="要预览的 Markdown 文件")
    args = parser.parse_args()

    # 创建 rich 控制台实例
    console = Console()
    file_path = Path(args.file).absolute()

    # 验证文件存在性
    if not file_path.exists():
        console.print(f"[bold red]错误: 文件 {file_path} 不存在！")
        sys.exit(1)
    if file_path.suffix.lower() != ".md":
        console.print("[yellow]警告: 文件扩展名不是 .md", style="yellow")

    # 初始化文件监视器
    event_handler = MarkdownHandler(file_path, console)
    observer = Observer()
    observer.schedule(event_handler, path=str(file_path.parent))
    observer.start()

    try:
        # 初始渲染
        event_handler.render_markdown()
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        console.print("\n[bold yellow]退出预览...")
    finally:
        observer.stop()
        observer.join()

if __name__ == "__main__":
    main()